using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
using Work.API.Applications.Write.Commands;
using Work.API.Dtos.DrugManagement;
using Work.ErrorCode;

namespace WinFormsApp1.DrugManagement
{
    /// <summary>
    /// 药品入库窗体（用于药品入库模块）
    /// 功能：
    /// 1. 药品入库（如果药品不存在则创建，如果存在则增加库存）
    /// 2. 记录入库批次信息（生产日期、有效期）
    /// 3. 修改药品信息和库存信息
    /// </summary>
    public partial class DrugInboundForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private List<DrugDto> _drugs;
        private bool _isEditMode = false; // 是否为编辑模式

        public DrugInboundForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            _drugs = new List<DrugDto>();

            // 初始化界面
            InitializeForm();
            
            // 在Load事件中加载药品列表，避免阻塞构造函数
            this.Load += DrugInboundForm_Load;
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void DrugInboundForm_Load(object? sender, EventArgs e)
        {
            // 在Load事件中异步加载药品列表，不阻塞UI线程
            // Load事件本身在UI线程上执行，LoadDrugList是async void，不会阻塞
            LoadDrugList();
        }

        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void InitializeForm()
        {
            // 设置默认值（只初始化实际存在的控件）
            // 注意：dtpProductionDate 和 dtpExpirationDate 已从药品信息管理部分移除，现在只在再次入库部分使用
            // 初始化批次信息字段的默认值（药品信息管理部分）
            if (dtpProductionDate != null)
                dtpProductionDate.Value = DateTime.Now;
            if (dtpExpirationDate != null)
                dtpExpirationDate.Value = DateTime.Now.AddYears(2);
            
            // 初始化再次入库部分的日期字段
            if (dtpReInboundProductionDate != null)
                dtpReInboundProductionDate.Value = DateTime.Now;
            if (dtpReInboundExpirationDate != null)
                dtpReInboundExpirationDate.Value = DateTime.Now.AddYears(2);
            _isEditMode = false;
            if (btnUpdateDrug != null)
                btnUpdateDrug.Enabled = false;
        }

        /// <summary>
        /// 创建药品（仅用于创建新药品，不再处理已存在药品的入库）
        /// </summary>
        private async void btnInboundDrug_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtDrugName.Text))
                {
                    MessageBox.Show("请输入药品名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(txtPurchasePrice.Text, out decimal purchasePrice))
                {
                    MessageBox.Show("请输入有效的进价", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(txtSellingPrice.Text, out decimal sellingPrice))
                {
                    MessageBox.Show("请输入有效的售价", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!int.TryParse(txtQuantity.Text, out int quantity) || quantity <= 0)
                {
                    MessageBox.Show("请输入有效的入库数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取库存上下限
                int upperLimit = int.TryParse(txtInventoryUpperLimit.Text, out int parsedUpperLimit) ? parsedUpperLimit : 10000;
                int lowerLimit = int.TryParse(txtInventoryLowerLimit.Text, out int parsedLowerLimit) ? parsedLowerLimit : 100;

                // 检查药品是否已存在（根据药品名称）
                var existingDrug = _drugs.FirstOrDefault(d => 
                    d.DrugName.Equals(txtDrugName.Text.Trim(), StringComparison.OrdinalIgnoreCase) && d.IsEnabled);

                if (existingDrug != null)
                {
                    MessageBox.Show($"药品'{txtDrugName.Text.Trim()}'已存在，请使用'再次入库'功能增加库存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证批次信息（如果填写了生产日期，有效日期必须晚于生产日期）
                if (dtpProductionDate != null && dtpExpirationDate != null)
                {
                    if (dtpExpirationDate.Value <= dtpProductionDate.Value)
                    {
                        MessageBox.Show("有效日期必须晚于生产日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }

                // 药品不存在，创建新药品并入库
                await CreateNewDrugAndInbound(purchasePrice, sellingPrice, quantity, upperLimit, lowerLimit);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建药品失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 创建新药品并入库
        /// </summary>
        private async System.Threading.Tasks.Task CreateNewDrugAndInbound(decimal purchasePrice, decimal sellingPrice, int quantity, int upperLimit, int lowerLimit)
        {
            // 检查入库数量是否在库存上下限范围内
            if (quantity < lowerLimit)
            {
                MessageBox.Show($"入库数量（{quantity}）小于库存下限（{lowerLimit}），不能入库。请调整入库数量，使其大于等于库存下限。",
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (quantity > upperLimit)
            {
                MessageBox.Show($"入库数量（{quantity}）大于库存上限（{upperLimit}），不能入库。请调整入库数量，使其小于等于库存上限。",
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var command = new CreateDrugCommand
            {
                DrugName = txtDrugName.Text.Trim(),
                DrugType = cmbDrugType.Text?.Trim(),
                CostName = cmbCostName.Text?.Trim(),
                DosageForm = cmbDosageForm.Text?.Trim(),
                Specification = cmbSpecification.Text?.Trim(),
                PurchasePrice = purchasePrice,
                SellingPrice = sellingPrice,
                Quantity = quantity,
                InventoryUpperLimit = upperLimit,
                InventoryLowerLimit = lowerLimit,
                Efficacy = txtEfficacy.Text?.Trim(),
                // 批次信息：从用户输入的控件中获取
                ProductionDate = dtpProductionDate?.Value ?? DateTime.Now,
                ExpirationDate = dtpExpirationDate?.Value ?? DateTime.Now.AddYears(2),
                BatchNumber = txtBatchNumber?.Text?.Trim() ?? "",
                Supplier = txtSupplier?.Text?.Trim() ?? "",
                Operator = "系统操作员", // 这里可以从登录信息获取
                Remarks = "" // 创建药品时备注为空
            };

            var json = JsonSerializer.Serialize(command);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsync("api/Drug/CreateDrug", content);
            response.EnsureSuccessStatusCode();
            var responseJson = await response.Content.ReadAsStringAsync();
            var apiResult = JsonSerializer.Deserialize<ApiResult<int>>(responseJson, _jsonOptions);

            if (apiResult != null && apiResult.Code == ApiEnum.成功)
            {
                MessageBox.Show("药品创建成功，入库记录已创建", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ClearForm();
                LoadDrugList(); // 刷新药品列表
            }
            else
            {
                MessageBox.Show(apiResult?.Message ?? "创建失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 再次入库按钮点击事件
        /// </summary>
        private async void btnReInbound_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtReInboundDrugName.Text))
                {
                    MessageBox.Show("请输入或选择药品名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取药品ID（优先使用隐藏字段，如果没有则根据名称查找）
                int drugId = 0;
                if (!string.IsNullOrWhiteSpace(txtReInboundDrugId.Text) && int.TryParse(txtReInboundDrugId.Text, out int parsedDrugId))
                {
                    drugId = parsedDrugId;
                }
                else
                {
                    // 根据药品名称查找
                    var drug = _drugs.FirstOrDefault(d => 
                        d.DrugName.Equals(txtReInboundDrugName.Text.Trim(), StringComparison.OrdinalIgnoreCase) && d.IsEnabled);
                    if (drug == null)
                    {
                        MessageBox.Show($"未找到药品'{txtReInboundDrugName.Text.Trim()}'，请先创建药品或从右侧列表选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    drugId = drug.DrugId;
                }

                if (!int.TryParse(txtReInboundQuantity.Text, out int quantity) || quantity <= 0)
                {
                    MessageBox.Show("请输入有效的入库数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取入库单价（如果未填写，使用药品的进价）
                decimal unitPrice = 0;
                if (!string.IsNullOrWhiteSpace(txtReInboundUnitPrice.Text))
                {
                    if (!decimal.TryParse(txtReInboundUnitPrice.Text, out unitPrice))
                    {
                        MessageBox.Show("请输入有效的入库单价", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                else
                {
                    // 如果未填写单价，使用药品的进价
                    var drug = _drugs.FirstOrDefault(d => d.DrugId == drugId);
                    if (drug != null)
                    {
                        unitPrice = drug.PurchasePrice;
                    }
                    else
                    {
                        MessageBox.Show("请输入入库单价", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }

                // 检查库存上限
                var selectedDrug = _drugs.FirstOrDefault(d => d.DrugId == drugId);
                if (selectedDrug != null)
                {
                    int newInventory = selectedDrug.Inventory + quantity;
                    if (newInventory > selectedDrug.InventoryUpperLimit)
                    {
                        int maxAllowed = selectedDrug.InventoryUpperLimit - selectedDrug.Inventory;
                        MessageBox.Show($"入库后库存（{newInventory}）将超过库存上限（{selectedDrug.InventoryUpperLimit}），不能入库。\n\n" +
                            $"当前库存：{selectedDrug.Inventory}\n" +
                            $"入库数量：{quantity}\n" +
                            $"最大允许入库数量：{maxAllowed}\n\n" +
                            $"请调整入库数量。",
                            "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }

                var command = new InboundDrugCommand
                {
                    DrugId = drugId,
                    Quantity = quantity,
                    UnitPrice = unitPrice,
                    ProductionDate = dtpReInboundProductionDate.Value,
                    ExpirationDate = dtpReInboundExpirationDate.Value,
                    BatchNumber = txtReInboundBatchNumber.Text?.Trim(),
                    Supplier = txtReInboundSupplier.Text?.Trim(),
                    Operator = "系统操作员", // 这里可以从登录信息获取
                    Remarks = txtReInboundRemarks.Text?.Trim()
                };

                var json = JsonSerializer.Serialize(command);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("api/Drug/InboundDrug", content);
                response.EnsureSuccessStatusCode();
                var responseJson = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<int>>(responseJson, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功)
                {
                    MessageBox.Show("再次入库成功，入库记录已创建", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearReInboundForm();
                    LoadDrugList(); // 刷新药品列表
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "再次入库失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"再次入库失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清空再次入库表单
        /// </summary>
        private void btnClearReInbound_Click(object sender, EventArgs e)
        {
            ClearReInboundForm();
        }

        /// <summary>
        /// 清空再次入库表单内容
        /// </summary>
        private void ClearReInboundForm()
        {
            txtReInboundDrugName.Text = "";
            txtReInboundDrugId.Text = "";
            txtReInboundQuantity.Text = "";
            txtReInboundUnitPrice.Text = "";
            txtReInboundBatchNumber.Text = "";
            txtReInboundSupplier.Text = "";
            txtReInboundRemarks.Text = "";
            dtpReInboundProductionDate.Value = DateTime.Now;
            dtpReInboundExpirationDate.Value = DateTime.Now.AddYears(2);
        }

        /// <summary>
        /// 修改药品信息
        /// </summary>
        private async void btnUpdateDrug_Click(object sender, EventArgs e)
        {
            try
            {
                if (!_isEditMode || string.IsNullOrWhiteSpace(txtDrugId.Text) || !int.TryParse(txtDrugId.Text, out int drugId))
                {
                    MessageBox.Show("请先选择要修改的药品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtDrugName.Text))
                {
                    MessageBox.Show("请输入药品名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(txtPurchasePrice.Text, out decimal purchasePrice))
                {
                    MessageBox.Show("请输入有效的进价", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(txtSellingPrice.Text, out decimal sellingPrice))
                {
                    MessageBox.Show("请输入有效的售价", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取库存上下限
                int upperLimit = int.TryParse(txtInventoryUpperLimit.Text, out int parsedUpperLimit) ? parsedUpperLimit : 10000;
                int lowerLimit = int.TryParse(txtInventoryLowerLimit.Text, out int parsedLowerLimit) ? parsedLowerLimit : 100;

                // 验证批次信息（如果填写了生产日期，有效日期必须晚于生产日期）
                if (dtpProductionDate != null && dtpExpirationDate != null)
                {
                    if (dtpExpirationDate.Value <= dtpProductionDate.Value)
                    {
                        MessageBox.Show("有效日期必须晚于生产日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }

                var command = new UpdateDrugCommand
                {
                    DrugId = drugId,
                    DrugName = txtDrugName.Text.Trim(),
                    DrugType = cmbDrugType.Text?.Trim(),
                    CostName = cmbCostName.Text?.Trim(),
                    DosageForm = cmbDosageForm.Text?.Trim(),
                    Specification = cmbSpecification.Text?.Trim(),
                    PurchasePrice = purchasePrice,
                    SellingPrice = sellingPrice,
                    InventoryUpperLimit = upperLimit,
                    InventoryLowerLimit = lowerLimit,
                    Efficacy = txtEfficacy.Text?.Trim(),
                    Operator = "系统操作员", // 这里可以从登录信息获取
                    // 批次信息：从"药品信息管理"部分的控件中获取
                    BatchNumber = txtBatchNumber?.Text?.Trim(),
                    Supplier = txtSupplier?.Text?.Trim(),
                    ProductionDate = dtpProductionDate?.Value,
                    ExpirationDate = dtpExpirationDate?.Value
                };

                var json = JsonSerializer.Serialize(command);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("api/Drug/UpdateDrug", content);
                response.EnsureSuccessStatusCode();
                var responseJson = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<int>>(responseJson, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功)
                {
                    MessageBox.Show("药品信息更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                    LoadDrugList(); // 刷新药品列表
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "更新失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改药品失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清空表单
        /// </summary>
        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        /// <summary>
        /// 清空表单内容
        /// </summary>
        private void ClearForm()
        {
            txtDrugName.Text = "";
            txtDrugId.Text = "";
            cmbDrugType.Text = "";
            cmbCostName.Text = "";
            cmbDosageForm.Text = "";
            cmbSpecification.Text = "";
            txtPurchasePrice.Text = "";
            txtSellingPrice.Text = "";
            txtQuantity.Text = "";
            txtInventoryUpperLimit.Text = "10000";
            txtInventoryLowerLimit.Text = "100";
            txtCurrentInventory.Text = ""; // 清空当前库存显示
            txtEfficacy.Text = "";
            // 清空批次信息字段
            if (txtBatchNumber != null)
                txtBatchNumber.Text = "";
            if (txtSupplier != null)
                txtSupplier.Text = "";
            if (dtpProductionDate != null)
                dtpProductionDate.Value = DateTime.Now;
            if (dtpExpirationDate != null)
                dtpExpirationDate.Value = DateTime.Now.AddYears(2);
            _isEditMode = false;
            btnUpdateDrug.Enabled = false;
        }

        /// <summary>
        /// 显示全部药品（刷新列表）
        /// </summary>
        private void btnShowAll_Click(object sender, EventArgs e)
        {
            LoadDrugList();
        }

        /// <summary>
        /// 加载药品库存列表
        /// </summary>
        private async void LoadDrugList()
        {
            try
            {
                // 检查窗体是否已释放
                if (this.IsDisposed || this.Disposing)
                {
                    return;
                }

                // 异步加载，不阻塞UI线程
                var response = await _httpClient.GetAsync("api/Drug/GetDrugs?onlyEnabled=true");
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugDto>>>(json, _jsonOptions);

                // 确保在UI线程上更新控件
                if (this.IsDisposed || this.Disposing)
                {
                    return;
                }

                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (!this.IsDisposed && !this.Disposing)
                        {
                            if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                            {
                                _drugs = apiResult.Data;
                                RefreshDrugListGridView();
                            }
                        }
                    }));
                }
                else
                {
                    if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                    {
                        _drugs = apiResult.Data;
                        RefreshDrugListGridView();
                    }
                }
            }
            catch (Exception ex)
            {
                // 确保在UI线程上显示错误消息
                if (this.IsDisposed || this.Disposing)
                {
                    return;
                }

                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (!this.IsDisposed && !this.Disposing)
                        {
                            MessageBox.Show($"加载药品列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }));
                }
                else
                {
                    MessageBox.Show($"加载药品列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 刷新药品列表表格
        /// </summary>
        private void RefreshDrugListGridView()
        {
            if (dgvDrugList != null)
            {
                // 添加DataError事件处理（如果还没有添加）
                dgvDrugList.DataError -= DgvDrugList_DataError;
                dgvDrugList.DataError += DgvDrugList_DataError;

                dgvDrugList.DataSource = null;
                dgvDrugList.DataSource = _drugs;
                SetDrugListColumnHeaders(dgvDrugList);
            }
        }

        /// <summary>
        /// 设置药品列表表格的中文列标题
        /// </summary>
        private void SetDrugListColumnHeaders(DataGridView dgv)
        {
            if (dgv.Columns.Count > 0)
            {
                var columnHeaders = new Dictionary<string, string>
                {
                    { "DrugId", "药品ID" },
                    { "DrugName", "药品名称" },
                    { "DrugType", "类型" },
                    { "CostName", "费用名称" },
                    { "DosageForm", "剂型" },
                    { "Specification", "规格" },
                    { "Inventory", "库存" },
                    { "InventoryUpperLimit", "库存上限" },
                    { "InventoryLowerLimit", "库存下限" },
                    { "PurchasePrice", "进价" },
                    { "SellingPrice", "售价" },
                    { "Efficacy", "功效" },
                    { "CreateTime", "创建时间" },
                    { "CreateBy", "创建人" },
                    { "UpdateTime", "更新时间" },
                    { "UpdateBy", "更新人" },
                    { "IsEnabled", "是否启用" }
                };

                // 先收集IsEnabled列的信息，避免在遍历时修改集合
                DataGridViewColumn? isEnabledColumn = null;
                int isEnabledColumnIndex = -1;

                // 第一遍遍历：设置列标题和格式，并找到IsEnabled列
                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    if (columnHeaders.ContainsKey(column.Name))
                    {
                        column.HeaderText = columnHeaders[column.Name];
                    }

                    // 格式化进价和售价为两位小数
                    if (column.Name == "PurchasePrice" || column.Name == "SellingPrice")
                    {
                        column.DefaultCellStyle.Format = "F2";
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    }

                    // 记录IsEnabled列的信息
                    if (column.Name == "IsEnabled")
                    {
                        isEnabledColumn = column;
                        isEnabledColumnIndex = column.Index;
                    }
                }

                // 第二遍：在循环外部处理IsEnabled列，避免修改集合时遍历
                if (isEnabledColumn != null && isEnabledColumnIndex >= 0)
                {
                    // 将列类型改为复选框
                    var checkBoxColumn = new DataGridViewCheckBoxColumn
                    {
                        Name = isEnabledColumn.Name,
                        HeaderText = isEnabledColumn.HeaderText,
                        DataPropertyName = isEnabledColumn.DataPropertyName,
                        ReadOnly = true,
                        Width = isEnabledColumn.Width
                    };
                    dgv.Columns.Remove(isEnabledColumn);
                    dgv.Columns.Insert(isEnabledColumnIndex, checkBoxColumn);
                    // 移除格式化事件处理器，因为复选框不需要格式化
                    dgv.CellFormatting -= DgvDrugList_IsEnabledFormatting;
                }
            }
        }

        /// <summary>
        /// 药品列表IsEnabled列的格式化事件
        /// </summary>
        private void DgvDrugList_IsEnabledFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if (sender is DataGridView dgv && e.ColumnIndex >= 0 && e.ColumnIndex < dgv.Columns.Count &&
                    dgv.Columns[e.ColumnIndex].Name == "IsEnabled")
                {
                    // 处理bool类型
                    if (e.Value is bool boolValue)
                    {
                        e.Value = boolValue ? "是" : "否";
                        e.FormattingApplied = true;
                        return;
                    }

                    // 处理可空bool类型
                    if (e.Value != null && e.Value is bool?)
                    {
                        bool? nullableBool = e.Value as bool?;
                        if (nullableBool.HasValue)
                        {
                            e.Value = nullableBool.Value ? "是" : "否";
                            e.FormattingApplied = true;
                            return;
                        }
                    }

                    // 处理字符串类型（可能已经是格式化后的值）
                    if (e.Value is string)
                    {
                        // 已经是字符串，不需要格式化
                        e.FormattingApplied = false;
                        return;
                    }
                }
            }
            catch
            {
                // 忽略格式化错误，使用默认显示
                e.FormattingApplied = false;
            }
        }

        /// <summary>
        /// DataGridView数据错误事件处理
        /// </summary>
        private void DgvDrugList_DataError(object? sender, DataGridViewDataErrorEventArgs e)
        {
            // 忽略数据错误，避免显示默认错误对话框
            e.ThrowException = false;
        }

        /// <summary>
        /// 选择药品列表中的药品（用于编辑和再次入库）
        /// </summary>
        private async void DgvDrugList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvDrugList.SelectedRows.Count > 0)
            {
                var selectedRow = dgvDrugList.SelectedRows[0];
                if (selectedRow.DataBoundItem is DrugDto drug)
                {
                    // 填充药品信息管理表单，进入编辑模式
                    _isEditMode = true;
                    txtDrugId.Text = drug.DrugId.ToString();
                    txtDrugName.Text = drug.DrugName;
                    cmbDrugType.Text = drug.DrugType ?? "";
                    cmbCostName.Text = drug.CostName ?? "";
                    cmbDosageForm.Text = drug.DosageForm ?? "";
                    cmbSpecification.Text = drug.Specification ?? "";
                    txtPurchasePrice.Text = drug.PurchasePrice.ToString("F2");
                    txtSellingPrice.Text = drug.SellingPrice.ToString("F2");
                    txtInventoryUpperLimit.Text = drug.InventoryUpperLimit.ToString();
                    txtInventoryLowerLimit.Text = drug.InventoryLowerLimit.ToString();
                    txtCurrentInventory.Text = drug.Inventory.ToString(); // 显示当前库存（只读）
                    txtEfficacy.Text = drug.Efficacy ?? "";
                    txtQuantity.Text = ""; // 编辑模式下，入库数量为空
                    btnUpdateDrug.Enabled = true;

                    // 异步获取第一条入库记录并反填批次信息
                    await LoadFirstInboundRecord(drug.DrugId);

                    // 同时填充再次入库表单
                    txtReInboundDrugId.Text = drug.DrugId.ToString();
                    txtReInboundDrugName.Text = drug.DrugName;
                    txtReInboundUnitPrice.Text = drug.PurchasePrice.ToString("F2"); // 默认使用进价
                    txtReInboundQuantity.Text = "";
                    txtReInboundBatchNumber.Text = "";
                    txtReInboundSupplier.Text = "";
                    txtReInboundRemarks.Text = "";
                    dtpReInboundProductionDate.Value = DateTime.Now;
                    dtpReInboundExpirationDate.Value = DateTime.Now.AddYears(2);
                }
            }
        }

        /// <summary>
        /// 加载第一条入库记录并反填批次信息到"药品信息管理"部分
        /// </summary>
        private async System.Threading.Tasks.Task LoadFirstInboundRecord(int drugId)
        {
            try
            {
                // 调用API获取该药品的所有入库记录
                var url = $"api/Drug/GetDrugInboundRecordsByDrugId?drugId={drugId}";
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugInboundDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null && apiResult.Data.Count > 0)
                {
                    // 按入库日期升序排序，取第一条（最早的入库记录）
                    var firstInbound = apiResult.Data
                        .OrderBy(di => di.InboundDate)
                        .ThenBy(di => di.CreateTime)
                        .FirstOrDefault();

                    if (firstInbound != null)
                    {
                        // 反填到"药品信息管理"部分的批次信息字段
                        if (txtBatchNumber != null)
                            txtBatchNumber.Text = firstInbound.BatchNumber ?? "";
                        if (txtSupplier != null)
                            txtSupplier.Text = firstInbound.Supplier ?? "";
                        if (dtpProductionDate != null)
                            dtpProductionDate.Value = firstInbound.ProductionDate ?? DateTime.Now;
                        if (dtpExpirationDate != null)
                            dtpExpirationDate.Value = firstInbound.ExpirationDate ?? DateTime.Now.AddYears(2);
                    }
                }
                else
                {
                    // 如果没有入库记录，使用默认值
                    if (txtBatchNumber != null)
                        txtBatchNumber.Text = "";
                    if (txtSupplier != null)
                        txtSupplier.Text = "";
                    if (dtpProductionDate != null)
                        dtpProductionDate.Value = DateTime.Now;
                    if (dtpExpirationDate != null)
                        dtpExpirationDate.Value = DateTime.Now.AddYears(2);
                }
            }
            catch (Exception ex)
            {
                // 静默失败，使用默认值，不影响用户操作
                // 可以记录日志，但不显示错误提示
                if (txtBatchNumber != null)
                    txtBatchNumber.Text = "";
                if (txtSupplier != null)
                    txtSupplier.Text = "";
                if (dtpProductionDate != null)
                    dtpProductionDate.Value = DateTime.Now;
                if (dtpExpirationDate != null)
                    dtpExpirationDate.Value = DateTime.Now.AddYears(2);
            }
        }
    }
}
